package com.dream.auth.config;

import com.dream.auth.config.security.service.UserDetailsServiceImpl;
import com.dream.auth.domain.models.LoginUser;
import com.dream.auth.web.service.TokenService;
import com.dream.base.redis.service.RedisService;
import com.dream.core.constant.Constants;
import com.dream.core.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * JwtTokenStoreConfig
 */
@Configuration
public class JwtTokenStoreConfig {
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    UserDetailsServiceImpl userDetailsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;
    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
   /* @Bean
    public KeyPair keyPair() {
        //从classpath下的证书中获取秘钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", "123456".toCharArray());
    }*/
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
       JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        accessTokenConverter.setSigningKey(secret);
        //accessTokenConverter.setKeyPair(keyPair());
        return accessTokenConverter;

    }
    @Bean
    public TokenEnhancer jwtTokenEnhancer(){
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                Map<String,Object> data = new HashMap<>();
                LoginUser loginUser = (LoginUser) authentication.getUserAuthentication().getPrincipal();
                String token=IdUtils.fastUUID();
                String userKey=  tokenService.getTokenKey(token);
                data.put(Constants.JWT_USER_TOKEN,userKey);
                tokenService.createToken(loginUser,token);

                ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(data);
                 return accessToken;
            }
        };
    }
}
